package com.runa.monitor.platinterface.extend.nb.utils;

import com.runa.protocol.util.UtilTime;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author: lyd
 * @Description: mqtt设置帮助类
 * @Date: 2021/7/8 13:24
 * @Version: 1.0
 */
public class MqttSetUtils {


    private static final Logger logger = LoggerFactory.getLogger(MqttSetUtils.class);

    /**
     * 应用key
     */
    public static String APP_KEY = "";
    /**
     * 应用秘钥
     */
    public static String APP_SECRET = "";

    /**
     * 温度面板产品id
     */
    public static String PANEL_PRODUCT_ID = "";
    /**
     * 温度面板-Master-APIkey
     */
    public static String PANEL_MASTER_KEY = "";

    /**
     * RU-STC-BT1温度面板产品id
     */
    public static String RU_PANEL_PRODUCT_ID = "";
    /**
     * RU-STC-BT1温度面板-Master-APIkey
     */
    public static String RU_PANEL_MASTER_KEY = "";
    /**
     * 楼表产品id
     */
    public static String BUILD_METER_PRODUCT_ID = "";
    /**
     * 楼表-Master-APIkey
     */
    public static String BUILD_METER_MASTER_KEY = "";
    /**
     * 楼阀产品id
     */
    public static String BUILD_VALVE_PRODUCT_ID = "";
    /**
     * 楼阀-Master-APIkey
     */
    public static String BUILD_VALVE_MASTER_KEY = "";
    /**
     * 温压监测仪产品id
     */
    public static String TEMPERATURE_PRESSURE_PRODUCT_ID = "";
    /**
     * 温压监测仪-Master-APIkey
     */
    public static String TEMPERATURE_PRESSURE_MASTER_KEY = "";


    /**
     * 校时时差（毫秒）
     */
    public static final int CHECK_TIME_SECOND = 6000;


    public static final String MBCX = "面板分离";


    /**
     * 检查唤醒周期是否超过 24小时30分钟
     * true:能发送  false:不能发送
     */
    public static boolean checkCanSendWakeUpCycle(Date addTime) {
        Date temp = UtilTime.addMinute(addTime, 1470);
        return System.currentTimeMillis() <= temp.getTime();
    }


    public static String getTemperaturePressureFactoryNameByType(String type) {
        if ("99".equals(type) || "1".equals(type) ) {
            return "瑞纳";
        }
        return null;
    }

    /**
     * 下发命令 ：TCP和LWM2M协议透传
     * <p>
     * deviceId        设备ID，（当指令级别为设备级时必填，为设备组级时则不填）
     * productId       产品ID，必填
     *
     * @param sendContent 指令内容，必填，格式为Json
     */
    /*public static String sendDownCommand(SendCmdConfigVo sendCmdConfigVo, String sendContent) {
        SendCmdDetailVo sendCmdDetailVo = new SendCmdDetailVo();
        //代表字符串
        sendCmdDetailVo.setDataType(1);
        sendCmdDetailVo.setPayload(sendContent);
        String responseMsg = null;
        try {
            AepDeviceCommandClient client = AepDeviceCommandClient.newClient()
                    .appKey(sendCmdConfigVo.getAppKey()).appSecret(sendCmdConfigVo.getAppSecret())
                    .build();
            CreateCommandRequest request = new CreateCommandRequest();
            request.setParamMasterKey(sendCmdConfigVo.getMasterKey());
            SendCmdBaseVo sendBaseVo = new SendCmdBaseVo();
            sendBaseVo.setDeviceId(sendCmdConfigVo.getDeviceId());
            //operator: 操作者，必填
            sendBaseVo.setOperator("runa");
            sendBaseVo.setProductId(sendCmdConfigVo.getProductId());
            //设备指令缓存时长，选填。单位：秒，取值范围：0-864000。 不携带则默认值：7200。如不需缓存请填0
            sendBaseVo.setTtl(7200);
            sendBaseVo.setContent(sendCmdDetailVo);
            String body = JSONObject.toJSONString(sendBaseVo);
            logger.info(sendCmdConfigVo.getTipMessage() + "---下发指令内容为：" + body);
            request.setBody(body.getBytes());
            CreateCommandResponse commandResponse = client.CreateCommand(request);
            responseMsg = new String(commandResponse.getBody(), StandardCharsets.UTF_8);
            logger.info(sendCmdConfigVo.getTipMessage() + "---下发命令返回的结果：{}", responseMsg);
            client.shutdown();
        } catch (Exception ex) {
            ex.printStackTrace();
            logger.info(sendCmdConfigVo.getTipMessage() + "---下发命令失败：" + ex.getMessage());
        }
        return responseMsg;
    }*/

    /**
     * 获取下发指令内容
     *
     * @param sendCmdParamVoList 下发指令参数
     * @return 下发指令内容
     *//*
    public static String getSendCmdByParamList(List<SendCmdParamVo> sendCmdParamVoList) {
        String sendContent = null;
        if (!CollectionUtils.isEmpty(sendCmdParamVoList)) {
            for (SendCmdParamVo sendCmdParamVo : sendCmdParamVoList) {
                if (StringUtils.isBlank(sendContent)) {
                    sendContent = sendCmdParamVo.getParamKey() + sendCmdParamVo.getParamValue();
                } else {
                    sendContent = sendContent + "," + sendCmdParamVo.getParamKey() + sendCmdParamVo.getParamValue();
                }
            }
        }
        return sendContent;
    }*/

    /**
     * 解析参数
     *
     * @param responseContent 响应内容
     * @return map 返回结果
     */
    public static Map<String, String> getParsingArgumentsMap(String responseContent) {
        Map<String, String> hashMap = null;
        if (StringUtils.isNotBlank(responseContent)) {
            String[] array = responseContent.split(",");
            hashMap = new HashMap<>();
            for (String string : array) {
                if (StringUtils.isNotBlank(string)) {
                    String[] itemArray = string.split(":");
                    if (itemArray.length >= 2) {
                        String key = itemArray[0];
                        String value = itemArray[1];
                        if (StringUtils.isNotBlank(key) && StringUtils.isNotBlank(value)) {
                            hashMap.put(key.trim(), value.trim());
                        }
                    }
                }
            }
        }
        return hashMap;
    }

    /*public static boolean checkEquDataValid(RedisUtil redisUtil, String equType, String typ, String serialNo) {
        boolean flag = false;
        int seconds = 120;
        try {
            switch (equType) {
                case "楼阀":
                    equType = "lv";
                    break;
                case "楼表":
                    equType = "lb";
                    break;
                default:
                    equType = "ot";
            }
            String redisKey = "meter:mqtt" + equType + ":" + typ + ":" + serialNo;
            String value = redisUtil.getStringValue(redisKey);
            if (StringUtils.isBlank(value)) {
                flag = true;
                redisUtil.setStringValue(redisKey, String.valueOf(System.currentTimeMillis()), seconds);
            } else {
                if (System.currentTimeMillis() - Long.parseLong(value) > seconds * 1000) {
                    flag = true;
                }
                redisUtil.setStringValue(redisKey, String.valueOf(System.currentTimeMillis()), seconds);
            }
        } catch (Exception exception) {
            //抛异常暂时pass掉
            flag = true;
            logger.info("验证电信平台上数的数据有效性,报错：{}", ExceptionUtils.getFullStackTrace(exception));
        }
        return flag;
    }*/

    public static boolean checkCanSendTc(Date addTime) {
        Date temp = UtilTime.addMinute(addTime, 1440);//超出24小时失效
        return System.currentTimeMillis() <= temp.getTime();
    }
}
